<?php
/**
 * @author zouhao zouhao619@gmail.com
 */
class WebChat{
	private $appID;
	private $appsecret;
	private $redirect_uri;
	private $scope='snsapi_userinfo';
	public function WebChat(){
		$this->appID=C('WEIXIN_APP_ID');
		$this->appsecret=C('WEIXIN_APP_SECRET');
		$this->redirect_uri='http://'.$_SERVER['HTTP_HOST'].U(C('WEIXIN_REDIRECT_URI'));
		$this->scope=C('WEIXIN_SCOPE');
	}
	public function get_login_url(){
		return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appID}&redirect_uri={$this->redirect_uri}&response_type=code&scope={$this->scope}&state=state#wechat_redirect";
	}
	/**
	 * 获取access_token及Openid
	 * @param String $code
	 * @return array
	 */
	public function get_user_access_token($code){
		$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appID}&secret={$this->appsecret}&code=${code}&grant_type=authorization_code";	
		return json_decode(curl_get($url),true);
	}
	/**
	 * 获取用户信息
	 * @param String $access_token
	 * @param String $openid
	 * @return array
	 */
	public function get_user_info($openid){
		$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->get_access_token()."&openid={$openid}";
		return json_decode(curl_get($url),true);
	}
	
	public function get_access_token(){
		$file=CONFIG_PATH.'/config.token.php';
		$access_token=require $file;
		if($access_token['expires_in']<=$_SERVER['REQUEST_TIME']){
			$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appID}&secret={$this->appsecret}";
			$access_token=json_decode(curl_get($url),true);
			$access_token['expires_in']=$_SERVER['REQUEST_TIME']+$access_token['expires_in'];
			file_put_contents($file,'<?php return ' . var_export ( $access_token, true ) . ';');
		}
		return $access_token['access_token'];
	}
	
	public function get_ticket(){
		$file=CONFIG_PATH.'/config.ticket.php';
		$ticket=require $file;
		if($ticket['expires_in']<=$_SERVER['REQUEST_TIME']){
			$url='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$this->get_access_token().'&type=jsapi';
			$ticket=json_decode(curl_get($url),true);
			$ticket['expires_in']=$_SERVER['REQUEST_TIME']+$ticket['expires_in'];
			file_put_contents($file,'<?php return ' . var_export ( $ticket, true ) . ';');
		}
		return $ticket['ticket'];
	}
	
}